﻿using System.IO;
using System;

namespace ShpMerger
{
    public class ShpFile
    {
        private Header header;
        private string shpFileName;
        private ExtendBinaryWriter extendBinaryWriter;
        private ExtendBinaryReader extendBinaryReader;
        private int recordNumber = 0;
        private ShapeFileOpenMode fileCurrentMode;

        public ShpFile(string fileName, ShapeFileOpenMode fileOpenMode)
        {
            this.fileCurrentMode = fileOpenMode;
            this.shpFileName = fileName;
            if (fileCurrentMode == ShapeFileOpenMode.FileCreate)
            {
                FileStream fileStream = new FileStream(shpFileName, FileMode.Create, FileAccess.Write);
                this.extendBinaryWriter = new ExtendBinaryWriter(fileStream);
                this.header = new Header();
                this.header.Write(extendBinaryWriter);
            }
            else
            {
                FileStream fileStream = new FileStream(shpFileName, FileMode.Open, FileAccess.Read);
                this.extendBinaryReader = new ExtendBinaryReader(fileStream);
                this.header = new Header();
                this.header.Read(this.extendBinaryReader);
            }
        }

        public void Close()
        {
            if (this.fileCurrentMode == ShapeFileOpenMode.FileCreate)
            {
                this.extendBinaryWriter.BaseStream.Position = 0;
                this.header.Write(extendBinaryWriter);
            }
            if (this.extendBinaryReader != null)
            {
                this.extendBinaryReader.Close();
            }
            if (this.extendBinaryWriter != null)
            {
                this.extendBinaryWriter.Close();
            }
        }

        public void Merge(ShpFile shpFile)
        {
            this.header.Merge(shpFile.header);
            while (shpFile.extendBinaryReader.BaseStream.Position < shpFile.extendBinaryReader.BaseStream.Length)
            {
                Record recordCurrent = new Record();
                recordCurrent.Read(shpFile.extendBinaryReader);
                recordNumber++;
                recordCurrent.RecordNumber = recordNumber;
                recordCurrent.Write(this.extendBinaryWriter);
            }
        }
    }
}
